package org.zjvis.datascience.common.widget.dto;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.zjvis.datascience.common.dto.BaseDTO;
import org.zjvis.datascience.common.util.DozerUtil;
import org.zjvis.datascience.common.util.JsonParseUtil;
import org.zjvis.datascience.common.widget.RelateWidget;
import org.zjvis.datascience.common.widget.WidgetDTOUtil;
import org.zjvis.datascience.common.widget.constant.WidgetJsonConstant;
import org.zjvis.datascience.common.widget.enums.RelatedWidgetStatusEnum;
import org.zjvis.datascience.common.widget.enums.WidgetTypeEnum;
import org.zjvis.datascience.common.widget.vo.WidgetVO;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description widget数据表 图表组件
 * @date 2021-12-22
 */
@Data
public class WidgetDTO extends BaseDTO {

    private Long id;

    //taskId 或者 datasetId 或者tabId
    private Long tid;

    private String type;

    private String name;

    private String dataJson;

    private String publishName;

    private String publishDataJson;

    private LocalDateTime publishTime;

    private String status;

    //正常来说，都是跟所在的dashboard 的 ID 相同，
    // 如果是-1 代表是项目级别 由 可视化视图 添加在节点上的
    // 如果是-2 代表该widget 已经被删除
    //https://cf.zjvis.org/pages/viewpage.action?pageId=32642583
    private Long dashboardId;

    //    //TODO
    private Long projectId;

    public WidgetVO view() {
        WidgetVO vo = DozerUtil.mapper(this, WidgetVO.class);
        JSONObject jsonObject = JSONObject.parseObject(this.getDataJson());
        vo.setData(jsonObject);
        if (jsonObject != null && jsonObject.containsKey(WidgetJsonConstant.CHART_OPTION)) {
            vo.setType(jsonObject.getJSONObject(WidgetJsonConstant.CHART_OPTION).getString(WidgetJsonConstant.DATA_TYPE));
        }
        vo.setPublishData(JSONObject.parseObject(this.getPublishDataJson()));
        return vo;
    }

    public RelateWidget toRelatedWidget(RelatedWidgetStatusEnum statusEnum) {
        RelateWidget relateWidget = new RelateWidget();
        relateWidget.setWidgetId(this.getId());
        relateWidget.setTaskId(this.getTid());
        relateWidget.setChartName(JsonParseUtil.getValueByKey("chartOptions.title", JSONObject.parseObject(this.getDataJson()), String.class));
        Pair<String, String> xAttrInfo = this.getXAttrInfo();
        relateWidget.setXAttrStr(xAttrInfo.getKey());
        relateWidget.setXAttrValueType(xAttrInfo.getValue());
        if (null != statusEnum) {
            relateWidget.setStatus(statusEnum.getDesc());
        }
        return relateWidget;
    }


    public Pair<String, String> getXAttrInfo() {
        //工具类报角标越界，手动取json
        String col = null;
        String desc = null;
        String config = WidgetDTOUtil.getValueByKey("widgetJson.config", this, String.class);
        JSONObject object = JSONObject.parseObject(config);
        JSONArray key = object.getJSONArray("keys");
        if (key != null) {
            JSONObject o = (JSONObject) key.get(0);
            String col1 = o.getString("col");
            String desc1 = o.getString("desc");
            col = col1;
            desc = desc1;
        }

        //  String col = WidgetDTOUtil.getValueByKey("widgetJson.config.keys[0].col", this, String.class);
        // String desc = WidgetDTOUtil.getValueByKey("widgetJson.config.keys[0].desc", this, String.class);
        if (StringUtils.isNotEmpty(col) && StringUtils.isNotEmpty(desc)) {
            return Pair.of(col, desc);
        } else if (StringUtils.isEmpty(col)) {
            return Pair.of(StringUtils.EMPTY, StringUtils.EMPTY);
        } else if (StringUtils.isEmpty(desc)) {
            return Pair.of(col, StringUtils.EMPTY);
        }
        return Pair.of(StringUtils.EMPTY, StringUtils.EMPTY);
    }

    /**
     * 是否是文本框类型widget
     *
     * @return
     */
    public boolean isTextType() {
        return this.getType().equalsIgnoreCase(WidgetTypeEnum.TEXT.getDesc());
    }

    /**
     * 是否是数据表格类型widget
     *
     * @return
     */
    public boolean isDataTableType() {
//        List<String> chartTypes = WidgetDTOUtil.getValueByKey("chartOptions.tables[0].chartType", this, JSONArray.class).toJavaList(String.class);
//        if (null != chartTypes && chartTypes.size() > 0) {
//            return chartTypes.stream().anyMatch(type -> type.equalsIgnoreCase(WidgetJsonConstant.DATA_TABLE_FLAG));
//        }
        return false;
    }

    public Boolean ifFromPipeline() {
        String nodeType = WidgetDTOUtil.getValueByKey("chartOptions.starNodeType", this, String.class);
        if (StringUtils.isNotEmpty(nodeType)) {
            return nodeType.equalsIgnoreCase(WidgetJsonConstant.DATASET_FLAG);
        }
        return false;
    }

    public boolean isFilterForm() {
        return this.getType().equalsIgnoreCase(WidgetTypeEnum.FILTER_FORM.getDesc());
    }

    public boolean isChartType() {
        Object value = WidgetDTOUtil.getValueByKey("chartType", this);
        if (!(value instanceof String)) {
            return ((JSONArray) value).toJavaList(String.class).stream()
                    .anyMatch(s -> s.toLowerCase().contains("chart") || s.toLowerCase().contains("plot"));
        }
        return false;
    }
}
